﻿using Consul;
using MediatR;
using Microsoft.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OfficeOpenXml;
using SmartProduction.Domain;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue;
using SmartProduction.Write.API.Application.Commands;
using SmartProduction.Write.API.Application.Commands.JobCommand_工作中心;
using System.Text;
using ClosedXML.Excel;
using SmartProduction.Write.API.Application.Commands.STaskCommand__生产管理;
using WorkflowCore.Interface;


namespace SmartProduction.Write.API.Controllers
{
    /// <summary>
    /// 工作中心
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class JobController : ControllerBase
    {
        private readonly ILogger<JobController> logger;
        private readonly IWorkflowHost workflowHost;
        private readonly IMediator mediator;
        private readonly DataDbContext db;
        private readonly IWorkflowHost workflow;

        public JobController(ILogger<JobController> logger, IWorkflowHost workflowHost,IMediator mediator, DataDbContext db, IWorkflowHost workflow)
        {
            this.logger = logger;
            this.workflowHost = workflowHost;
            this.mediator = mediator;
            this.db = db;
            this.workflow = workflow;
        }
        [HttpPost("start")]
        public async Task<IActionResult> StartWorkFlow([FromBody] Approval data)
        {
            var id = await workflow.StartWorkflow("JobLevelApprovalWorkflow", 1, data);
            return Ok(new { WorkFlowId = id });
        }
        /// <summary>
        /// 新增工作中心
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> AddJob(JobAddCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 删除工作中心
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<APIResult<object>> DelJob([FromQuery] JobDelCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 修改工作中心
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<APIResult<object>> UpdJob(JobUpdateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
     
       
        
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
      //  [HttpPost]
        //public async Task<IActionResult> UploadFile(IFormFile file)
        //{
        //    if (file == null || file.Length == 0)
        //    {
        //        return BadRequest("请选择一个文件上传");
        //    }
        //    try
        //    {
        //        using (var stream = new MemoryStream())
        //        {
        //            await file.CopyToAsync(stream);
        //            using (var package = new ExcelPackage(stream))
        //            {
        //                StringBuilder builder = new StringBuilder();
        //                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        //                int rowCount = worksheet.Dimension.Rows;
        //                int columnCount = worksheet.Dimension.Columns;

        //                for (int row = 2; row <= rowCount; row++)
        //                {
        //                    Job job = new Job();
        //                    for (int col = 1; col <= columnCount; col++)
        //                    {
        //                        switch (col)
        //                        {
        //                            case 1:
        //                                job.JobNode = worksheet.Cells[row, col].Value.ToString();
        //                                break;
        //                            case 2:
        //                                job.JobName = worksheet.Cells[row, col].Value.ToString();
        //                                break;
        //                            case 3:
        //                                job.JobType = worksheet.Cells[row, col].Value.ToString();
        //                                break;
        //                            case 4:
        //                                job.Shift = worksheet.Cells[row, col].Value.ToString();
        //                                break;
        //                        }
        //                    }
        //                    db.Jobs.Add(job);
        //                }
        //                int i = await db.SaveChangesAsync();
        //                if (i > 0)
        //                {
        //                    return new JsonResult(new { success = true, msg = "导入成功" });
        //                }
        //                else
        //                {
        //                    return new JsonResult(new { error = true, msg = "导入失败，没有数据被保存" });
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        // 记录日志
        //        // 可以使用日志框架如 NLog、Serilog 等
        //        Console.WriteLine($"导入失败: {ex.Message}");
        //        return new JsonResult(new { success = false, msg = $"导入失败: {ex.Message}" });
        //    }
        //}
        /// <summary>
        /// 导入工作中心管理
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportInventories(IFormFile file)
        {
            APIResult<string> result = new APIResult<string>();
            try
            {
                // 检查上传文件是否为空
                if (file == null || file.Length <= 0)
                {
                    result.Code = APIEnums.查询失败;
                    result.Msg = "未上传文件或文件为空";
                    return BadRequest(result);
                }

                // 检查文件扩展名是否为 Excel 格式
                var fileExtension = Path.GetExtension(file.FileName);
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                {
                    result.Code = APIEnums.查询失败;
                    result.Msg = "仅支持上传 Excel 文件";
                    return BadRequest(result);
                }

                // 使用 MemoryStream 读取文件内容
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    using (var workbook = new XLWorkbook(stream))
                    {
                        var worksheet = workbook.Worksheet(1); // 获取第一个工作表
                        var rows = worksheet.RowsUsed().Skip(1); // 跳过第一行（表头）

                        List<Job> job = new List<Job>();

                        foreach (var row in rows)
                        {
                            var jobs = new Job();
                            jobs.JobNode = row.Cell(1).GetValue<string>();
                            jobs.JobName = row.Cell(2).GetValue<string>();
                            jobs.JobType = row.Cell(3).GetValue<string>();
                            jobs.Shift = row.Cell(4).GetValue<string>();
                            jobs.ApprovalStatus = row.Cell(5).GetValue<int>();
                            jobs.CreatedBy = row.Cell(6).GetValue<int>();
                            jobs.CreatedTime = row.Cell(7).GetValue<DateTime>();
                            jobs.UpdatedBy = row.Cell(8).GetValue<int>();
                            jobs.UpdatedTime = row.Cell(9).GetValue<DateTime>();
                            jobs.Status = row.Cell(10).GetValue<int>();
                            jobs.IsDelete = row.Cell(11).GetValue<int>();

                            // 添加到要插入的列表中
                            job.Add(jobs);
                        }
                        await db.AddRangeAsync(job);
                        await db.SaveChangesAsync();
                        result.Code = APIEnums.添加成功;
                        result.Msg = "导入成功";
                        result.data = job.Count.ToString();
                    }
                }
            }
            catch (Exception ex)
            {

                result.Code = APIEnums.添加失败;
                result.Msg = "导入失败，原因：" + ex.Message;
                return StatusCode(500, result);
            }
            return Ok(result);
        }
        /// <summary>
        /// 新增生产任务
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<STask>> STaskAdd(STaskAddCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 删除生产任务
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<APIResult<object>> STaskDel([FromQuery]STaskDelCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
